const router = require('koa-router')()
const EventEmitter = require('events');
const { Buffer } = require('buffer');
const path = require('path')
const fs = require('fs')
const formidable = require('formidable');
const CreateSequelize = require('./sequelize')
let Sequelize = require('sequelize')
let sequelize = new CreateSequelize()
const {
  DataTypes,
  Op
} = require('sequelize')
sequelize.init_sequeleze()
router.prefix('/JFChatMsg')


const STATIC_TEMPORARY = path.resolve(__dirname, '../public/temporary');

const STATIC_FILES = path.resolve(__dirname, '../public/files');



const records = sequelize.db.define('records', {
  uuid: {
    type: DataTypes.UUID,
    comment: '自增长id',
    defaultValue: Sequelize.UUIDV4
  },
  from_id: {
    type: DataTypes.STRING,
    comment: '发消息的人'
  },
  to_id: {
    type: DataTypes.STRING,
    comment: '收消息的人'
  },
  name: {
    type: DataTypes.STRING,
    comment: '用户备注'
  },
  msg: {
    type: DataTypes.STRING(10000),
    comment: '发送信息'
  },
  time: {
    type: DataTypes.STRING,
    comment: '发送时间'
  },
  headImg: {
    type: DataTypes.STRING,
    comment: '用户头像'
  },
  isRead: {
    type: DataTypes.INTEGER,
    comment: '已读未读消息 （0未读，1已读）'
  },
}, {
  timestamps: true, // 开启时间戳
})
//获取朋友列表
// router.get('/getUserInfo', async function (ctx, next) {
//   // let newData = await records.findAll()
//   let newData = await sequelize.select("select * from friends");
//   ctx.body = newData
// })

//查找和我相关的信息
router.post('/getdata', async (ctx, next) => {
  let { from_id, to_id } = ctx.request.body
  let datalist = [];
  //获取本地和别人聊天的信息
  let data = await records.findAll({
    where: {
      from_id: from_id,
      to_id: to_id
    },
  })
  data.forEach((item) => {
    datalist.push(item)
  })
  //获取别人和本地的聊天信息
  let list = await records.findAll({
    where: {
      from_id: to_id,
      to_id: from_id
    },
  })
  list.forEach((item) => {
    datalist.push(item)
  })
  //合并数组以后进行排序
  datalist = datalist.sort((a, b) => { return a.id - b.id })
  //返回这个列表
  ctx.body = datalist
})


//文件上传
router.post('/upload', async (ctx, next) => {
  let form = new formidable.IncomingForm();
  const myEmitter = new EventEmitter();
  form.hash = "md5";
  form.multiples = true; //默认只能上传一个文件,更多form的配置参考node-formidable
  form.maxFileSize = 100 * 1024 * 1024; //设置文件最大不超过2M
  const formData = {
    filename: undefined,
    hash: undefined,
    chunk: undefined,
  }
  let isFieldOk = false, isFileOk = false;
  async function formImage() {
    return new Promise((resolve, reject) => {
      form.parse(ctx.req, async function (err, fields, files) { //注意：跟express有差异，这里要传入ctx.req
        console.log(fields, '*****')
        formData.filename = fields['filename'];
        formData.hash = fields['hash'][0];

        isFieldOk = true;
        myEmitter.emit('start')
      })
      form.on('file', function (name, file) {
        formData.chunk = file;
        isFileOk = true;
        myEmitter.emit('start')
      })

      myEmitter.on('start', function () {
        if (isFieldOk && isFileOk) {
          const { filename, hash, chunk } = formData;
          const dir = `${STATIC_TEMPORARY}/${filename}`;
          try {
            if (!fs.existsSync(dir)) fs.mkdirSync(dir);
            const buffer = fs.readFileSync(chunk.filepath);
            const ws = fs.createWriteStream(`${dir}/${hash}`);
            ws.write(buffer);
            ws.close();
            console.log(`${filename}-${hash} 切片上传成功`)
          } catch (error) {
            console.error(error);
          }

          isFieldOk = false;
          isFileOk = false;
        }
      });
    })
  }
  await formImage()
    .then(res => ctx.body('切片上传成功'))
    .catch(err => ctx.body("上传失败"));
});
//文件合并
router.post('/merge', async (ctx, next) => {
  const { filename } = ctx.request.body;
  console.log(filename, '合并的参数名称');
  let dir;
  try {
    let len = 0;
    const bufferList = fs.readdirSync(`${STATIC_TEMPORARY}/${filename}`).map(hash => {
      const buffer = fs.readFileSync(`${STATIC_TEMPORARY}/${filename}/${hash}`);
      len += buffer.length;
      return buffer;
    });

    const buffer = Buffer.concat(bufferList, len);
    const ws = fs.createWriteStream(`${STATIC_FILES}/${filename}`);
    ws.write(buffer);
    ws.close();
    dir = `http://localhost:3030/files/${filename}`
    console.log(`切片合并完成`);
  } catch (error) {
    console.error(error);
  }
  ctx.body = {
    msg: '合并',
    url: dir
  }
})

//获取详情
router.post('/getUserItem', async (ctx, next) => {
  let searchVal = ctx.request.body.val
  let messages = []
  let data = await records.findAll({})
  let firends = await sequelize.select("select * from friends");
  let list = data.filter((item) => {
    return item.msg === searchVal
  })
  list.forEach((item) => {
    firends.forEach((ite) => {
      if (item.to_id === ite.fromId) {
        ite.msg = item.msg
        messages.push(ite)
      }
    })
  })
  let firendsList = firends.filter((item) => {
    return item.remark === searchVal
  })
  ctx.body = {
    firendsList,
    messages
  }
})


router.post('/getmessage', async (ctx, next) => {
  console.log(ctx.request.body, '=====000000');
  let id = ctx.request.body.id
  const sql = `SELECT
	* 
FROM
	(
	SELECT
		* 
	FROM
		records
	WHERE
		time IN (
		SELECT
			MAX( time ) 
		FROM
    records 
		WHERE
			from_id = '${id}' 
			OR to_id = '${id}'  
		GROUP BY
			CONCAT(
			IF
				( from_id > to_id, from_id, to_id ),
			IF
			( from_id < to_id, from_id, to_id ))) 
		AND ( to_id = '${id}'  OR from_id = '${id}') 
	ORDER BY
		id DESC 
	) c 
ORDER BY
  c.time DESC`;
  let result = []
  let recordss = await sequelize.select(sql);
  console.log(recordss, '----');
  let newData = await sequelize.select("select * from friends");
  let asd = await records.findAll();
  newData.forEach((item) => {
    asd.forEach((ite) => {
      if (item.toId === ite.from_id && item.fromId === ite.to_id && ite.isRead === 0) {
        console.log(item);
        result.push(item)
      }
    })
  })
  newData.forEach((item) => {
    recordss.forEach((ite) => {
      if (item.toId === ite.to_id || item.fromId !== ite.from_id) {
        item.msg = ite.msg
        item.time = ite.time
      }
    })
  })
  ctx.body = {
    newData,
    result
  }
})

//标记为未读消息
router.post('/changeIsRead', async (ctx, next) => {
  console.log(ctx.request.body, '===');
  await records.update({
    isRead: 0
  }, {
    where: {
      from_id: ctx.request.body.id
    }
  })
  ctx.body = "修改成功"
})

//删除聊天记录
router.post('/delMessage', async (ctx, next) => {
  console.log(ctx.request.body, '===');
  const { fromId, toId } = ctx.request.body

  await records.destroy({
    where: {
      from_id: fromId,
      to_id: toId
    }
  })
  ctx.body = "删除成功"
})


module.exports = router